import java.util.*;

public class FindPairs {

    public static void main(String[] args) {
        FindPairs findPairs = new FindPairs();
        int[] nums = {1,3,1,5,4};
        System.out.println(findPairs.findPairs(nums, 0));
    }

    public int findPairs1(int[] nums, int k) {
        int ans = 0;
        HashMap<Integer, Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && map.get(nums[i]) == 1) ++ans;
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        if (k == 0) return ans;
        ans = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer key = entry.getKey();
            if (map.containsKey(key + k)) ++ans;
        }
        return ans;
    }

    public int findPairs2(int[] nums, int k) {
        Arrays.sort(nums);
        int ans = 0;
        int r = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i == 0 || nums[i] != nums[i - 1]) {
                while (r < nums.length && (nums[i] + k > nums[r] || r <= i)) ++r;
                if (nums[r] == nums[i]) ++ans;
            }
        }
        return ans;
    }

    public int findPairs(int[] nums, int k) {
        Arrays.sort(nums);
        Set<Integer> visited = new HashSet<>();
        Set<Integer> ans = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (visited.contains(nums[i] - k)) ans.add(nums[i] - k);
            visited.add(nums[i]);
        }
        return ans.size();
    }
}
